package cn.virens.web.components.rabbit;

import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;

public abstract class RabbitListener implements ChannelAwareMessageListener, InitializingBean {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	protected final Charset charset = Charset.forName("UTF-8");

	@Autowired
	protected AmqpAdmin mAmqpAdmin;

	@Value("${rabbit.exchange}")
	protected String exchange;

	@Value("${rabbit.prefetch.size}")
	protected int prefetchSize;

	@Value("${rabbit.prefetch.count}")
	protected int prefetchCount;

	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		channel.basicQos(prefetchSize, prefetchCount, true);

		// 解析数据包
		JSONObject json = JSON.parseObject(new String(message.getBody(), charset));
		if (json != null && !json.isEmpty()) {
			this.onHandler(message, channel, json);
		} else {
			channel.basicAck(deliveryTag(message), false);
		}
	}

	/**
	 * 消息处理
	 * 
	 * @param message 消息信息
	 * @param channel 通道实例
	 * @param json    消息数据
	 */
	protected abstract void onHandler(Message message, Channel channel, JSONObject json);

	protected static long deliveryTag(Message message) {
		return message.getMessageProperties().getDeliveryTag();
	}

}
